<script setup lang="ts">
import {onMounted, reactive, h, ref} from "vue";
import {NTag, NButton, NDivider, NDropdown} from "naive-ui";
import {Search} from "@vicons/tabler"
import {clone} from "@renderer/utils/index"

const formRef = ref<HTMLFormElement | null>(null);
const searchForm = reactive({
  name: '',
  catid: '',
  current: 1,
  size: 10
})
let operator = ref('Add')
const showModal = ref(false);
const modalTitle = ref("添加产品")
//表单数据
let formData = ref({
  catid: '',
  name: '',
  brand: '',
  code: '',
  license: '',
  capacity: '',
  price: 0,
  stock: 0,
  enabled: '1'
})
// 校验规则
const rules = reactive({
  catid: {
    required: true,
    message: '请选择商品分类',
    trigger: 'change'
  },
  name: {
    required: true,
    message: '请输入商品名称',
    trigger: 'blur'
  },
  price: {
    required: true,
    message: '请输入商品价格',
    trigger: 'blur'
  },
  stock: {
    required: true,
    message: '请输入商品库存',
    trigger: 'blur'
  },
  enabled: {
    required: true,
    message: '请选择状态',
    trigger: 'change'
  },
})
// 表格数据
let tableData = ref({
  page: [],
  total: 0
})
let categories = reactive([])

const columns = reactive([
  {
    title: '序号',
    key: 'id',
    width: '60px',
    align: 'center',
    render: (_, index) => {
      return `${index + 1}`
    }
  },
  {
    title: '商品名称',
    key: 'name',
    width: '150px',
    fixed: 'left'
  },
  {
    title: '商品分类',
    key: 'catname',
    width: '150px',
    fixed: 'left',
    render: (row) => {
      for(let i = 0;i < categories.length; i++){
        if(categories[i].value == row.catid){
          return categories[i].label
        }
      }
    }
  },
  {
    title: '品牌',
    key: 'brand',
    width: '80px',
  },
  {
    title: '货号',
    key: 'code',
    width: '80px',
  },
  {
    title: '生产许可证',
    key: 'license',
    width: '100px',
  },
  {
    title: '售价',
    key: 'price',
    width: '100px',
  },
  {
    title: '库存',
    key: 'stock',
    width: '100px',
  },
  {
    title: '状态',
    key: 'enabled',
    width: '80px',
    align: 'center',
    render: (row) => {
      if(row.enabled == 1) {
        return h(
            NTag,
            {
              type: 'success',
              size: 'small'
            },
            { default: () => '启用' }
        )
      }else{
        return h(
            NTag,
            {
              type: 'default',
              size: 'small'
            },
            { default: () => '禁用' }
        )
      }
    }
  },
  {
    title: '操作',
    key: 'enabled',
    fixed: 'right',
    width: '150px',
    render: (row) => {
      return [
        h(
            NButton,
            {
              type: 'warning',
              size: 'tiny',
              secondary: true,
              strong: true,
              onClick: () => handleToUpdateClick(row)
            },
            { default: () => '编辑' }
        ),
        h(NDivider,
            {
              vertical: true
            },
            null
        ),
        h(
            NButton,
            {
              type: 'error',
              size: 'tiny',
              secondary: true,
              strong: true,
              onClick: () => handleDeleteClick(row.id)
            },
            { default: () => '删除' }
        ),
        h(NDivider,
            {
              vertical: true
            },
            null
        ),
        h(NDropdown, {
              trigger: 'hover',
              options: [{
                label: '滨海湾金沙，新加坡',
                key: 'marina bay sands',
              }],
              onSelect: (key) => handleSelectClick(key, row.id)
            },
            {default: () => '...'})
      ]
    }
  }
])

const handleSelectClick = (key, id) => {
  console.log(key, id)
}

// 搜索
const handleSearchClick = () => {
  loadData()
}
// 分页
const handlePageChange = (page) => {
  searchForm.current = page
  loadData()
}
// 添加弹窗
const handleToAddClick = () => {
  modalTitle.value = '添加产品'
  operator.value = 'Add'
  formData.value = {
    catid: '',
    name: '',
    brand: '',
    code: '',
    license: '',
    capacity: '',
    price: 0.00,
    stock: 0,
    enabled: '1'
  }
  showModal.value = true
}
const handleToUpdateClick = (row) => {
  modalTitle.value = '编辑产品'
  operator.value = 'Edit'
  formData.value = clone(row)
  formData.value.enabled += ''
  formData.value.price += ''
  formData.value.stock += ''
  showModal.value = true
}
// 添加
const handleSaveClick = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      if(operator.value == 'Add'){
        window.electron.ipcRenderer.invoke("renderer-to-main", {
          name: 'app-product-add',
          event: 'event',
          data: clone(formData.value)
        })
      } else {
        window.electron.ipcRenderer.invoke("renderer-to-main", {
          name: 'app-product-update',
          event: 'event',
          data: clone(formData.value)
        })
      }
    }
  })
}

// 加载表格数据
const loadData = () => {
  window.electron.ipcRenderer.invoke("renderer-to-main", {
    name: 'app-product-page',
    event: 'event',
    data: clone(searchForm)
  })
}
//加载会员等级
const loadCategories = () => {
  window.electron.ipcRenderer.invoke("renderer-to-main", {
    name: 'app-productcat-all',
    event: 'event',
    data: {}
  })
}
// 删除
const handleDeleteClick = (id) => {
  window.electron.ipcRenderer.invoke("renderer-to-main", {
    name: 'app-product-delete',
    event: 'event',
    data: id
  })
}

onMounted(() => {
  window.electron.ipcRenderer.on('main-to-renderer', (e, data) => {
    const event = data.data
    if(data.name === 'product-page-success'){
      tableData.value = event
    }else if(data.name === 'category-all-success'){
      categories = event
    }else if(data.name === 'product-operator-success'){
      window.$message.success(event);
      showModal.value = false
      loadData()
    }
  })
  loadCategories()
  loadData()
})
</script>

<template>
  <n-space vertical>
    <div class="dreamer-search">
      <n-form inline :label-width="80" :model="searchForm" size="small">
        <n-form-item  label="商品分类" path="searchForm.catid">
          <n-select v-model:value="searchForm.catid" :options="categories" clearable placeholder="选择商品分类" style="width: 200px" />
        </n-form-item>
        <n-form-item  label="商品名称" path="searchForm.name">
          <n-input v-model:value="searchForm.name" clearable placeholder="输入商品名称" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" attr-type="button" @click="handleSearchClick">
            <template #icon>
              <n-icon>
                <Search />
              </n-icon>
            </template>
            搜索
          </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div class="dreamer-toolbar">
      <n-button type="primary" size="small" @click="handleToAddClick">添加</n-button>
    </div>
    <n-data-table :columns="columns" :data="tableData.records" size="small" striped bordered :scroll-x="1150" />

    <div class="dreamer-pagination">
      <n-pagination v-model:page="searchForm.current" :page-count="tableData.pages" :on-update:page="handlePageChange" />
    </div>
  </n-space>

  <n-modal :title="modalTitle" v-model:show="showModal" :mask-closable="false" :show-icon="false" preset="dialog" size="small" style="width: 500px">
    <n-form ref="formRef" :label-width="80" :model="formData" :rules="rules" size="small">
      <n-grid x-gap="12" :cols="2">
        <n-gi :span="24">
          <n-form-item label="商品名称" path="name">
            <n-input v-model:value="formData.name" placeholder="请输入商品名称" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="商品分类" path="catid">
            <n-select v-model:value="formData.catid" :options="categories" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="品牌" path="brand">
            <n-input v-model:value="formData.brand" placeholder="请输入品牌" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="商品货号" path="code">
            <n-input v-model:value="formData.code" placeholder="请输入商品货号" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="生产许可证号" path="license">
            <n-input v-model:value="formData.license" placeholder="请输入生产许可证号" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="净含量" path="capacity">
            <n-input v-model:value="formData.capacity" placeholder="请输入净含量" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="售价" path="price">
            <n-input v-model:value="formData.price" placeholder="请输入售价" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="库存" path="stock">
            <n-input v-model:value="formData.stock" placeholder="请输入库存" />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item label="状态" path="enabled">
            <n-radio-group v-model:value="formData.enabled">
              <n-space>
                <n-radio label="启用" value="1" />
                <n-radio label="禁用" value="0" />
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-gi>
      </n-grid>

      <div class="dreamer-modal-footer">
        <n-space>
          <n-button type="default" size="small" attr-type="button" @click="showModal = false">取消</n-button>
          <n-button type="primary" size="small" attr-type="button" @click="handleSaveClick">保存</n-button>
        </n-space>
      </div>
    </n-form>
  </n-modal>
</template>

<style scoped lang="less">
:deep(.n-form-item-label){
  color: #333333 !important;
}
</style>
